<?php
namespace app\common\model\member;

use app\common\model\BaseModel;
use org\util\HelpUtil;
use think\facade\Session;
use think\facade\Validate;

class MemberModel extends BaseModel
{
    protected $name = 'member';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 添加用户
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addData($data){
        try{
            if(!empty($data['username']) && $this->where('username',$data['username'])->find()){
                exception('该用户名已存在！',40001);
            }
            if(!empty($data['email']) && $this->where('email',$data['email'])->find()){
                exception('该邮箱已存在！',40001);
            }
            if(!empty($data['mobile']) && $this->where('mobile',$data['mobile'])->find()){
                exception('该手机号已存在！',40001);
            }
            $data['salt'] = HelpUtil::randString(8);
            $data['password'] = $this->getEncryptPassword($data['password'],$data['salt']);
            if(empty($data['username'])){
                $data['username'] = 'm'.$data['mobile'];
            }
            $data['birthday'] = empty($data['birthday']) ? null : $data['birthday'];
            self::create($data);
        }catch (\Exception $e){
            exception($e->getMessage());
        }
        return true;
    }

    /**
     * 修改用户
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editData($data){
        try{
            $info = $this->where('id',$data['id'])->find();
            if($info['username']!=$data['username']
                && $this->where('username',$data['username'])->find()){
                exception('该用户名已存在！',40001);
            }
            if(!empty($data['email'])
                && $info['email']!=$data['email']
                && $this->where('email',$data['email'])->find()){
                exception('该邮箱已存在！',40001);
            }
            if(!empty($data['mobile'])
                && $info['mobile']!=$data['mobile']
                && $this->where('mobile',$data['mobile'])->find()){
                exception('该手机号已存在！',40001);
            }
            if(empty($data['password'])){
                unset($data['password']);
            }else{
                $data['password'] = $this->getEncryptPassword($data['password'],$info['salt']);
            }
            $data['birthday'] = empty($data['birthday']) ? null : $data['birthday'];
            self::update($data);
        }catch (\Exception $e){
            exception($e->getMessage());
        }
        return true;
    }
    /**
     * 获取密码加密后的字符串
     * @param string $password  密码
     * @param string $salt      密码种子
     * @return string
     */
    public function getEncryptPassword($password, $salt ='') {
        return md5(sha1($password) . $salt);
    }

    /**
     * 用户登录
     * @param string    $account    账号:用户名、邮箱、手机号
     * @param string    $password   密码
     * @return boolean
     */
    public function login($account, $password)
    {
        $field = $this->getAccountField($account);
        $info = $this->where($field,$account)->find();
        if (!$info) exception('用户不存在！',40001);
        if($info['status']!=1) exception('该账户已禁用！',40001);
        if($info['password']!=$this->getEncryptPassword($password,$info['salt'])) exception('密码不正确！',40001);
        //直接登录会员
        $this->setLoginInfo($info['id']);
        return true;
    }
    /**
     * 退出登录
     * @return bool
     * @throws \Exception
     */
    public function loginOut(){
        if(!Session::has('member')){
            exception('未登录！',40001);
        }
        Session::delete('member');
        return true;
    }
    /**
     * 修改密码
     * @param $memberId
     * @param $newPassword
     * @param string $oldPassword
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changepwd($memberId,$newPassword, $oldPassword = '')
    {
        $info = $this->where('id',$memberId)->find();
        //验证旧密码，为空跳过验证直接修改密码
        if($info['password']==$this->getEncryptPassword($oldPassword,$info['salt']) || $oldPassword==''){
            $this->where('id',$memberId)->setField('password',$this->getEncryptPassword($newPassword,$info['salt']));
            $this->loginOut();
        }else{
            exception('原密码不正确！',40001);
        }
        return true;
    }
    /**
     * 设置登录成功信息
     * @param $adminId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setLoginInfo($adminId){
        $map[]=['id','=',$adminId];
        $loginInfo = $this->getInfo($map);
        unset($loginInfo['password'],$loginInfo['salt'],$loginInfo['points'],$loginInfo['frozen_points']);
        Session::set('member',$loginInfo);
        return true;
    }
    /**
     * 区分账户所属字段
     * @param $account
     * @return string
     */
    public function getAccountField($account){
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        return $field;
    }
}